package hasthi.actuators.actions;

import javax.xml.namespace.QName;

import hasthi.actuators.ResourceBasedAction;
import hasthi.actuators.SystemConfig;
import hasthi.actuators.impl.HostAgentBasedHostProxy;
import hasthi.common.HasthiException;
import hasthi.common.HasthiException.FaultCode;
import hasthi.common.constants.WSDMConstants;
import hasthi.config.DeploymentConfig;
import hasthi.config.ResourceProfile;
import hasthi.container.MessageContext;
import hasthi.container.SimpleMessageContext;
import hasthi.container.UnicastContianier;
import hasthi.metamodel.resource.ManagedResource;
import hasthi.metamodel.resource.ManagedService;
import edu.indiana.extreme.wsdm.ShutDownRequestDocument;
import edu.indiana.extreme.wsdm.ShutDownRequestDocument.ShutDownRequest;

public class SafeShutDownAction extends ResourceBasedAction {
    private String name;
    public SafeShutDownAction(ManagedResource resource) {
        super(resource);
        name =  "ShutDownAction#" + resource.getName();
    }
    @Override
    public void execute() throws HasthiException {
        SystemConfig systemConfig = actionContext.getSystemConfig();
        ResourceProfile resourceProfile = systemConfig.getResourceProfile(QName.valueOf(resource.getType()));
        if (resourceProfile != null && resourceProfile.getDeployment() != null &&
                resource instanceof ManagedService 
                && resourceProfile.getDeployment().getShutDownCommand() != null ) {
            DeploymentConfig deploymentConfig = resourceProfile.getDeployment(); 
            String hostName = ((ManagedService)resource).getHost();
            ManagedResource deployHost = actionContext.getResourceModel().getResource(new QName(hostName));
            if(deployHost != null){
                HostAgentBasedHostProxy remoteSystemProxy = new HostAgentBasedHostProxy(actionContext.getBaseContext(),
                        deployHost.getManagerAgentURL(), actionContext.getUnicastContainer());
                remoteSystemProxy.runCommand(hostName, deploymentConfig.getShutDownCommand(), null,
                        deploymentConfig.getInstallDir(), false, "");
            }else{
                throw new HasthiException("ShutDown only supported with host Agent "+ hostName, FaultCode.ConfigError);
            }
        }else{
            ShutDownRequestDocument requestDocument = ShutDownRequestDocument.Factory.newInstance();
            ShutDownRequest shutDownRequest = requestDocument.addNewShutDownRequest();
            MessageContext message = new SimpleMessageContext(shutDownRequest,resource.getManagerAgentURL(),
                        WSDMConstants.ACTION_SHUTDOWN);
            UnicastContianier container = actionContext.getUnicastContainer();
            container.sendReceive(message);
        }
    }
    @Override
    public String getActionID() {
        return name;
    }

    @Override
    public String toString() {
        return name;
    }
}
